package com.strust2.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;
import com.struts2.util.ATTSystem;

public class BaseAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	protected Map<String, Object> ajaxMap = new HashMap<String, Object>();
	protected Integer pageNo;
	protected Integer pageSize;
	protected String message;
	
	/**
	 * 获取HttpServletRequest对象
	 * @return
	 */
	public HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	/**
	 * 获取HttpServletResponse对象
	 * @return
	 */
	public HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	/**
	 * 获取HttpSession对象
	 * @return
	 */
	public HttpSession getSession(){
		return this.getRequest().getSession(true);
	}
	/**
	 * 添加Cookie
	 * @param key
	 * @param value
	 * @param domain
	 */
	public void addCookie(String key, String value){
		try {
			HttpServletResponse response = this.getResponse();
			Cookie cookie = new Cookie(key, value);
			cookie.setPath("/");
			response.addCookie(cookie);
		} catch (Exception e) {
		}
	}
	/**
	 * 获取Cookie
	 * @param key
	 * @return
	 */
	public String getCookie(String key){
		HttpServletRequest request = this.getRequest();
		Cookie[] cookies = request.getCookies();
		String val = null;
		for(Cookie c : cookies){
			if(key.equals(c.getName())){
				val = c.getValue();
				break;
			}
		}
		return val;
	}
	/**
	 * 获取请求IP
	 * @return
	 */
	public String getClientIp(){
		HttpServletRequest request = this.getRequest();
		String ip = request.getHeader(ATTSystem.HTTP_HEAD_REMOTE_ADDR);
		if (ip == null) {
			ip = request.getRemoteAddr();
		}
		if (!StringUtils.isEmpty(ip)) {
			ip = ip.split(",")[0];
		}
		return ip;
	}
	
	public Map<String, Object> getAjaxMap() {
		return ajaxMap;
	}
	public void setAjaxMap(Map<String, Object> ajaxMap) {
		this.ajaxMap = ajaxMap;
	}
	public Integer getPageNo() {
		return pageNo;
	}
	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}
	public Integer getPageSize() {
		return pageSize;
	}
	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}
